#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author       : Abmer
# @Date         : 2019-08-06 10:30:22
# @Link         : https://gitee.com/edrik
# @Modified by  : Amber
# @Modified at  : 2019-08-31 09:51:11
# @Version      : v.0.1

import json


class GlobalKV:
    """cross-file global variables"""
    webview = None
    hwnd = None
    app = None
    exstate = None
    main_frame = None
    kv = {}
    ioc = {}
    script = {}

    @staticmethod
    def set(key, val):
        self = GlobalKV
        if isinstance(val, dict):
            val = json.dumps(val)
        self.kv[key] = val

    def set_kv(self, **keys):
        self.kv.update(keys)

    def delete(self, key):
        return self.kv.pop(key)

    @staticmethod
    def get(*args):
        self = GlobalKV
        dic = {}
        if len(args) == 1:
            key = args[0]
            if 'all' == key:
                return self.kv

            if hasattr(self, key):
                '''if key is class.attribute'''
                print('getattr %s' % key)
                return getattr(self, key)
            '''find value in self.kv'''
            return self.kv.get(key)

        for key in args:
            dic[key] = self.kv.get(key)

        return dic


# ctx = GlobalKV()
GLKV = GlobalKV


def add_script(name, fn):
    GLKV.script[name] = fn


def set_script(name):
    return GLKV.script.get(name)


def add_ioc(name, fn):
    GLKV.ioc[name] = fn


def get_ioc(name):
    return GLKV.ioc.get(name)


def get(*name):
    return GLKV.get(*name)


def set_kv(**kwargs):
    GLKV.set_kv(**kwargs)


def set(name, value):
    GLKV.set(name, value)


def _set_webview(webview):
    GLKV['webview'] = webview


def _set_hwnd(hwnd):
    get['hwnd'] = hwnd


def webview():
    return get('webview')


def hwnd():
    return get('hwnd')


def main_frame():
    return get('main_frame')


def ex_state():
    return get('exstate')
